package com.dst.smart.handler.disposer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.dst.smart.app.MainActivity;
import com.dst.smart.constant.Constants;
import com.dst.smart.music.MusicPlayMedia;
import com.dst.smart.player.VolumeManager;
import com.dst.smart.threadpool.ThreadPoolTaskSong;
import com.dst.smart.tools.AppTools;
import com.dst.smart.handler.entity.SemanticResult;
import com.dst.smart.handler.entity.ServiceType;
import com.dst.smart.player.entity.SongPlayInfo;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

/**
 * 音乐结果处理器。
 * 
 * author <a href="http://www.xfyun.cn">讯飞开放平台</a>
 * date 2016年6月21日 下午4:29:54
 *
 */
public class MusicDisposer extends Disposer {
	private final static String INSTYPE_SLEEP = "sleep";
	private final static String INSTYPE_BROADCAST = "broadcast";
	private final static String INSTYPE_BROADCASTSINGER = "broadcastsinger";
	private final static String KEY_OPERATION = "operation";
	private final static String KEY_SEMANTIC = "semantic";
	private final static String KEY_SLOTS = "slots";
	private final static String KEY_INSTYPE = "insType";
	private final static String KEY_STATE = "used_state";
	private final static String KEY_MISMATCH = "mismatch{artist,song}";
	private final static String OPERATION_INS = "INSTRUCTION";


	private final static String INSTYPE_NEXT = "next";
	private final static String INSTYPE_PAST = "past";
	private final static String INSTYPE_REPLAY = "replay";
	private final static String INSTYPE_REPEAT = "repeat";
	private final static String INSTYPE_PAUSE = "pause";

	private final static String INSTYPE_REPLAYANSWER = "replayAnswer";

	private final static String INSTYPE_VOLMAX = "volume_max";
	private final static String INSTYPE_VOLMID = "volume_mid";
	private final static String INSTYPE_VOLMIN = "volume_min";
	private final static String INSTYPE_VOLMINUS = "volume_minus";
	private final static String INSTYPE_VOLPLUS = "volume_plus";
	private final static String VOLUME_SELECT = "volume_select";

	private VolumeManager mVolumeManager;
	private boolean isIncrease = false;
	private boolean PlaySource = false;
	enum INSTYPE {
		NEXT, PAST, REPLAY, REPEAT, PAUSE, VOLMAX, VOLMID, VOLMIN, VOLMINUS, VOLPLUS, INSTYPE_REPLAYANSWER,VOLUME_SELECT
	};

	private static Map<String, INSTYPE> insTypeMap;

	static {
		insTypeMap = new HashMap<String, INSTYPE>();
		insTypeMap.put(INSTYPE_NEXT, INSTYPE.NEXT);
		insTypeMap.put(INSTYPE_PAST, INSTYPE.PAST);
		insTypeMap.put(INSTYPE_REPLAY, INSTYPE.REPLAY);
		insTypeMap.put(INSTYPE_REPEAT, INSTYPE.REPEAT);
		insTypeMap.put(INSTYPE_PAUSE, INSTYPE.PAUSE);
		insTypeMap.put(INSTYPE_VOLMAX, INSTYPE.VOLMAX);
		insTypeMap.put(INSTYPE_VOLMID, INSTYPE.VOLMID);
		insTypeMap.put(INSTYPE_VOLMIN, INSTYPE.VOLMIN);
		insTypeMap.put(INSTYPE_VOLMINUS, INSTYPE.VOLMINUS);
		insTypeMap.put(INSTYPE_VOLPLUS, INSTYPE.VOLPLUS);
		insTypeMap.put(INSTYPE_REPLAYANSWER, INSTYPE.INSTYPE_REPLAYANSWER);
		insTypeMap.put(VOLUME_SELECT,INSTYPE.VOLUME_SELECT);
	}
	private int currentVolume = -1;
	public MusicDisposer(Context context) {
		super(context);
	}

	@Override
	public void disposeResult(final SemanticResult result) {
		try {
			if (result != null) {
				String operation = result.getOperation();

				mVolumeManager = VolumeManager.getInstance();

				if (OPERATION_INS.equals(operation)) {
					// ���隞�
					JSONObject semantic = result.getSemantic();
					String insType = semantic.getJSONObject(KEY_SLOTS).getString(
							KEY_INSTYPE);
					if (INSTYPE_SLEEP.equals(insType)) {
						// 隡��
						Intent intent = new Intent();
						intent.setAction(Constants.ACTION_SLEEP);
						mContext.sendBroadcast(intent);

						return;
					} else if (INSTYPE_NEXT.equals(insType)) {

					} else if (INSTYPE_REPLAY.equals(insType)) {
					/*
					if (PlaySource) {

					} else {
						if (MusicPlayMedia.getInstansMedia() != null) {
							if(MainActivity.recordSong!=null){
								MusicPlayMedia.getInstansMedia().setFileName(1,
										MainActivity.recordSong.content);
								try {
									MusicPlayMedia.getInstansMedia().play();
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
					}
					*/
					} else if (INSTYPE_PAUSE.equals(insType)) {
						// ����
						if (PlaySource) {

						} else {
							if ((MusicPlayMedia.getInstansMedia() != null)
									&& MainActivity.musicPlaySt) {
								MusicPlayMedia.getInstansMedia().pause();
							}
						}
					}
					INSTYPE type = insTypeMap.get(insType);
					// ����
					if (null != type) {
						switch (type) {
							case VOLMAX: {
								if (PlaySource) {
									if (null != mVolumeManager) {
										mVolumeManager.setMaxVolume();
									}
								} else {
									if (MusicPlayMedia.getInstansMedia() != null) {
										MusicPlayMedia.setVolume(100);
									}
								}
							}
							break;

							case VOLMIN: {
								if (PlaySource) {
									if (null != mVolumeManager) {
										mVolumeManager.setMinVolume();
									}
								} else {
									if (MusicPlayMedia.getInstansMedia() != null) {
										MusicPlayMedia.setVolume(10);
									}
								}
							}
							break;

							case VOLMID: {
								if (PlaySource) {
									if (null != mVolumeManager) {
										mVolumeManager.setMidVolume();
									}
								} else {
									if (MusicPlayMedia.getInstansMedia() != null) {
										MusicPlayMedia.setVolume(50);
									}
								}
							}
							break;

							case VOLPLUS: {
								if (PlaySource) {
									isIncrease = true;
//								playPromptTone();
								} else {
									if (MusicPlayMedia.getInstansMedia() != null) {
										MusicPlayMedia.setUpVolume();
									}
								}
							}
							break;

							case VOLMINUS: {
								if (PlaySource) {
									isIncrease = false;
//								playPromptTone();
								} else {
									if (MusicPlayMedia.getInstansMedia() != null) {
										MusicPlayMedia.setDownVolume();
									}
								}
							}
							break;
							case VOLUME_SELECT:
								String volun = semantic.getJSONObject(KEY_SLOTS).getString("series");
								if (AppTools.isNumeric(volun)) {
									if (MusicPlayMedia.getInstansMedia() != null) {
										MusicPlayMedia.getInstansMedia().setPlayerVolume(volun);
										MusicPlayMedia.getInstansMedia().setVolume();
									}
								}
								break;
							case NEXT: {
								//MusicPlayMedia.getInstansMedia().next();
							}
							break;
							case PAST: {
								//MusicPlayMedia.getInstansMedia().previous();
							}
							break;
							case PAUSE: {
								//MusicPlayMedia.getInstansMedia().pause();
							}
							break;
							case REPLAY: {
								//MusicPlayMedia.getInstansMedia().continuePlay();
							}
							break;
							default:
								break;
						}
					}
					return;
				}

				List<SongPlayInfo> songInfos = parseMusicList(result);
				JSONArray song = result.getResult();

				if (null != song && song.length() > 0) {
					parseMusicJson(result);
					String text = result.getAnswerText();
					JSONObject songInfoJson = song.getJSONObject(0);
					String audiopath = songInfoJson.optString("audiopath");
					if (!TextUtils.isEmpty(audiopath)) {
						if (MainActivity.musicIsSong) {
							try {
								if (MusicPlayMedia.getInstansMedia() == null) {
									new MusicPlayMedia(mContext, "");
								}
								final Random random = new Random();
								MainActivity.sleepLight = random.nextInt(7) + 1;
								MusicPlayMedia.getInstansMedia().playURLList(songInfos);
								MusicPlayMedia.getInstansMedia().setFileName(1,
										audiopath, 0);
								MusicPlayMedia.getInstansMedia().play();
							} catch (Exception e) {
								// TODO: handle exception
							}
						}
					}
					sendAiuiData("音乐", "musicX", result.toString());
				} else {
					getPlayController().playURLList(result.getUUID(), null);
					getPlayController().playText(result.getUUID(), result.getAnswerText(), true, "", null);
				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
	}
	
	public boolean canHandle(ServiceType type){
		return (type == ServiceType.MUSICX);
	}

	private void parseMusicJson(SemanticResult semanticResult) {

		try {
			JSONArray result = semanticResult.getResult();
			
			if (null != result && result.length() > 0) {
				for (int i = 0; i < result.length(); i++) {

					JSONObject songInfoJson = result.getJSONObject(i);
					String singernames = songInfoJson.getString("singernames");
					ThreadPoolTaskSong songThread = new ThreadPoolTaskSong(	singernames,
								singernames, "music",
								songInfoJson.optString("audiopath"),
								songInfoJson.optString("songname"));
					MainActivity.activity.poolManager.addAsyncTask(songThread);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	private List<SongPlayInfo> parseMusicList(SemanticResult semanticResult) {

		try {
			JSONArray result = semanticResult.getResult();

			if (null != result && result.length() > 0) {
				List<SongPlayInfo> songPlayInfos = new ArrayList<SongPlayInfo>();

				for (int i = 0; i < result.length(); i++) {

					JSONObject songInfoJson = result.getJSONObject(i);


					SongPlayInfo playInfo = new SongPlayInfo();

					playInfo.setSongName(songInfoJson.optString("songname"));
					playInfo.setPlayUrl(songInfoJson.optString("audiopath"));

					JSONArray singernames = songInfoJson.optJSONArray("singernames");
					if (singernames != null && singernames.length() > 0) {
						StringBuffer singerName = new StringBuffer();
						for (int j = 0; j < singernames.length(); j++) {
							singerName.append(singernames.optString(j) + ",");
						}

						playInfo.setSingerName(singerName.toString());
					}
					if(i == 0){
						playInfo.setAnswerText(semanticResult.getAnswerText());
					}

					songPlayInfos.add(playInfo);
				}
				return songPlayInfos;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return null;
	}
	
}
